package com.magicode.screen;

import static com.magicode.screen.AppConfig.KEY_FRITST_START;
import static com.magicode.screen.AppConfig.KEY_LOAD_IMAGE;
import static com.magicode.screen.AppConfig.KEY_TWEET_DRAFT;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import java.util.UUID;

import com.loopj.android.http.MySSLSocketFactory;
import com.magicode.screen.api.ApiHttpClient;
import com.magicode.screen.base.BaseApplication;
import com.magicode.screen.bean.Constants;
import com.magicode.screen.bean.User;
import com.magicode.screen.cache.DataCleanManager;
import com.magicode.screen.util.CyptoUtils;
import com.magicode.screen.util.MethodsCompat;
import com.magicode.screen.util.StringUtils;
import com.magicode.screen.util.UIHelper;

import org.kymjs.kjframe.KJBitmap;
import org.kymjs.kjframe.utils.KJLoger;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.PersistentCookieStore;

/**
 * 全局应用程序类：用于保存和调用全局应用配置及访问网络数据
 * 
 * @author 火蚁 (http://my.oschina.net/LittleDY)
 * @version 1.0
 * @created 2014-04-22
 */
public class AppContext extends BaseApplication {

    public static final int PAGE_SIZE = 10;// 默认分页大小

    private static AppContext instance;
    private boolean sslFlag = true;
    private String loginUid;//用户Id
    private String picNormalPath;//用户头像
    private String loginName;//用户登录名
    private String userName;//用户名
    private String password;//密码
    private String userToken;
    private String userTokenRefreshTime;
    private int vipday;//vip天
    private boolean login;
//    英文版日期格式
    public static SimpleDateFormat engFormat = new SimpleDateFormat("MMM dd,yyyy");
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        init();
        initLogin();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();

    }
    private void init() {
        // 初始化网络请求
        AsyncHttpClient client = null;
        if(sslFlag ==true){
            client = new AsyncHttpClient(true, 80, 443);
            client.setSSLSocketFactory(MySSLSocketFactory.getFixedSocketFactory());
        }
        else{
            client = new AsyncHttpClient();
        }
        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        client.setCookieStore(myCookieStore);
        String serverDomain = null;
        String serverHost = null;

        serverDomain = UIHelper.getServerDomain(this);
        serverHost = UIHelper.getServerHost(this);
        System.out.println("***************serverDomain:"+serverDomain);
        System.out.println("***************serverHost:"+serverHost);
        ApiHttpClient.setApiUrl(serverDomain);
        ApiHttpClient.setHOST(serverHost);
        ApiHttpClient.setHttpClient(client);
        ApiHttpClient.setCookie(ApiHttpClient.getCookie(this));

        // Log控制器
        KJLoger.openDebutLog(true);



    }

    private void initLogin() {

        User user = getLoginUser();
        if (null != user && user.getId() != null) {
            login = true;
            loginUid = user.getId();
        } else {
            this.cleanLoginInfo();
        }
    }

    /**
     * 获得当前app运行的AppContext
     * 
     * @return
     */
    public static AppContext getInstance() {
    	javax.xml.parsers.DocumentBuilder a = null;
        return instance;
    }

    public boolean containsProperty(String key) {
        Properties props = getProperties();
        return props.containsKey(key);
    }

    public void setProperties(Properties ps) {
        AppConfig.getAppConfig(this).set(ps);
    }

    public Properties getProperties() {
        return AppConfig.getAppConfig(this).get();
    }

    public void setProperty(String key, String value) {
        AppConfig.getAppConfig(this).set(key, value);
    }

    /**
     * 获取cookie时传AppConfig.CONF_COOKIE
     * 
     * @param key
     * @return
     */
    public String getProperty(String key) {
        String res = AppConfig.getAppConfig(this).get(key);
        return res;
    }

    public void removeProperty(String... key) {
        AppConfig.getAppConfig(this).remove(key);
    }

    /**
     * 获取App唯一标识
     * 
     * @return
     */
    public String getAppId() {
        String uniqueID = getProperty(AppConfig.CONF_APP_UNIQUEID);
        if (StringUtils.isEmpty(uniqueID)) {
            uniqueID = UUID.randomUUID().toString();
            setProperty(AppConfig.CONF_APP_UNIQUEID, uniqueID);
        }
        return uniqueID;
    }

    /**
     * 获取App安装包信息
     * 
     * @return
     */
    public PackageInfo getPackageInfo() {
        PackageInfo info = null;
        try {
            info = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace(System.err);
        }
        if (info == null)
            info = new PackageInfo();
        return info;
    }

    /**
     * 保存登录信息
     * 
     * @param user
     */
    @SuppressWarnings("serial")
    public void saveUserInfo(final User user) {
        this.loginUid = user.getUserId();
        this.picNormalPath=user.getPicNormalPath();
        this.loginName=user.getLoginName();
        this.userName=user.getUserName();
        this.password=user.getPassword();
        this.userToken=user.getUserToken();
        this.userTokenRefreshTime=user.getUserTokenRefreshTime();
        this.login = true;
        setProperties(new Properties() {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            {
            	if(user.getUserId() != null){
            		setProperty("user.userId", user.getUserId() );
            	}
            	if(user.getUserName() != null){            		
            		setProperty("user.userName", user.getUserName());
            	}
            	if(user.getLoginName() != null){   
                setProperty("user.loginName", user.getLoginName());// 用户头像-文件名
            	}
            	if(user.getPassword() != null){
                setProperty("user.password",
                        CyptoUtils.encode("MagicodeApplication", user.getPassword()));
            	}
                if(user.getEncPassword() != null){
                setProperty("user.encPassword", user.getEncPassword());
                }
            	if(user.getPicMinPath() != null){   
                setProperty("user.picMinPath", user.getPicMinPath());
            	}
            	if(user.getPicNormalPath() != null){   
                setProperty("user.picNormalPath",user.getPicNormalPath());
            	}
                if(user.getUserToken() != null){
                    setProperty("user.userToken",user.getUserToken());
                }
                if(user.getUserTokenRefreshTime() != null){
                    setProperty("user.userTokenRefreshTime",user.getUserTokenRefreshTime());
                }
            }
        });
    }


    /**
     * 更新用户信息
     * 
     * @param user
     */
    @SuppressWarnings("serial")
    public void updateUserInfo(final User user) {
    	saveUserInfo(user);
//        setProperties(new Properties() {
//            {
//            	 setProperty("user.userId", user.getId());
//                 setProperty("user.userName", user.getUserName());
//                 setProperty("user.loginName", user.getLoginName());// 用户头像-文件名
//                 setProperty("user.password",
//                         CyptoUtils.encode("MagicodeApplication", user.getEncPassword()));
//                 setProperty("user.picMinPath", user.getPicMinPath());
//                 setProperty("user.picNormalPath",user.getPicNormalPath());
//            }
//        });
    }

    /**
     * 获得登录用户的信息
     * 
     * @return
     */
    public User getLoginUser() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(getProperty("user.userId") == null){
            return null;
        }
        User user = new User();
        user.setId(getProperty("user.userId"));
        user.setUserId(user.getId());
        user.setUserName(getProperty("user.userName"));
        user.setLoginName(getProperty("user.loginName"));
        user.setPassword(CyptoUtils.decode("MagicodeApplication", getProperty("user.password")));
        user.setEncPassword(getProperty("user.encPassword"));
//        CyptoUtils.decode("MgcApp", getProperty("user.password"))
        user.setPicMinPath(getProperty("user.picMinPath"));
        user.setPicNormalPath(getProperty("user.picNormalPath"));
        user.setUserToken(getProperty("user.userToken"));
        user.setUserTokenRefreshTime(getProperty("user.userTokenRefreshTime"));

        return user;
    }

    /**
     * 是否为专业版会员
     * @return
     */
    public boolean isVipUser(){
        boolean result = false;
        User user = getLoginUser();
        Date cDate = new Date();
        if( user != null && user.getVipEndTime() != null){
            if( cDate.compareTo(user.getVipEndTime()) <= 0 ){
                result = true;
            }
        }
        return result;
    }
    /**
     * 清除登录信息
     */
    public void cleanLoginInfo() {
        this.loginUid = "";
        this.login = false;
        removeProperty("user.userId", "user.userName", "user.loginName", "user.password","user.encPassword",
                "user.picMinPath", "user.picNormalPath","user.userToken","user.userTokenRefreshTime");
    }
    /**
     * 清除login
     */
    public void cleanLogin() {
        this.login = false;
    }

    /**
     * 用户注销
     */
    public void Logout() {
        cleanLoginInfo();
        ApiHttpClient.cleanCookie();
        this.cleanCookie();

        this.login = false;
        this.loginUid = "";

        Intent intent = new Intent(Constants.INTENT_ACTION_LOGOUT);
        sendBroadcast(intent);
    }

    /**
     * 清除保存的缓存
     */
    public void cleanCookie() {
        removeProperty(AppConfig.CONF_COOKIE);
    }

    /**
     * 清除app缓存
     */
    public void clearAppCache() {
  //      DataCleanManager.cleanDatabases(this); // 清除数据缓存

        DataCleanManager.cleanInternalCache(this);

        // 2.2版本才有将应用缓存转移到sd卡的功能

        if (isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)) {
            DataCleanManager.cleanCustomCache(MethodsCompat.getExternalCacheDir(this));
        }
        // 清除编辑器保存的临时内容
        Properties props = getProperties();
        for (Object key : props.keySet()) {
            String _key = key.toString();
            if (_key.startsWith("temp"))
                removeProperty(_key);
        }
        new KJBitmap().cleanCache();
    }

    public static void setLoadImage(boolean flag) {
        set(KEY_LOAD_IMAGE, flag);
    }

    /**
     * 判断当前版本是否兼容目标版本的方法
     * 
     * @param VersionCode
     * @return
     */
    public static boolean isMethodsCompat(int VersionCode) {
        int currentVersion = android.os.Build.VERSION.SDK_INT;
        return currentVersion >= VersionCode;
    }

    public static String getTweetDraft() {
        return getPreferences().getString(
                KEY_TWEET_DRAFT + getInstance().getLoginUid(), "");
    }

    public static void setTweetDraft(String draft) {
        set(KEY_TWEET_DRAFT + getInstance().getLoginUid(), draft);
    }

    public static String getNoteDraft() {
        return getPreferences().getString(
                AppConfig.KEY_NOTE_DRAFT + getInstance().getLoginUid(), "");
    }

    public static void setNoteDraft(String draft) {
        set(AppConfig.KEY_NOTE_DRAFT + getInstance().getLoginUid(), draft);
    }

    public static boolean isFristStart() {
        return getPreferences().getBoolean(KEY_FRITST_START, true);
    }

    public static void setFristStart(boolean frist) {
        set(KEY_FRITST_START, frist);
    }


    /**
     * 判断语言
     * 1.中国;
     * 2.美国(目前使用非中国)
     * @return
     */
    public static int getLanguage(){
        int result = 1;
        Locale l = Locale.getDefault();

        String language = l.getLanguage();
        String country = l.getCountry().toLowerCase();
        if ("zh".equals(language)) {
           result = 1;
        }
        else{
            result = 2;
        }
        return result;
    }

    public String getLoginUid() {
        return loginUid;
    }

    public void setLoginUid(String loginUid) {
        this.loginUid = loginUid;
    }

    public String getPicNormalPath() {
        return picNormalPath;
    }

    public void setPicNormalPath(String picNormalPath) {
        this.picNormalPath = picNormalPath;
    }

    public String getLoginName() {
        return loginName;
    }

    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserToken() {
        return userToken;
    }

    public void setUserToken(String userToken) {
        this.userToken = userToken;
    }

    public String getUserTokenRefreshTime() {
        return userTokenRefreshTime;
    }

    public void setUserTokenRefreshTime(String userTokenRefreshTime) {
        this.userTokenRefreshTime = userTokenRefreshTime;
    }

    public int getVipday() {
        return vipday;
    }

    public void setVipday(int vipday) {
        this.vipday = vipday;
    }

    public boolean isLogin() {
        return login;
    }

    public void setLogin(boolean login) {
        this.login = login;
    }
}
